import React, { Component } from 'react';
import ThePagination from "@/components/ThePagination";
import { Form, Input, Select, message, Table, Tag, Space, Button, DatePicker, Modal, Row, Col, InputNumber } from "antd";
import { SearchOutlined, ExclamationCircleOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import GoBack from '@/components/TheGoBack'
import { apiStockTakeListAddBefore, apiStockTakeListView, apiStockTakeInfoAdd, apiStockTakeListAdd, apiStockTakeInfoDel, apiStockTakeListExecute } from '@/request/storageManager/stock.js'
import { apiGetGoodsList, apiAdd, apiEdit, apiGetGoodsDetail, apiView } from '@/request/marketingTool'
import moment from 'moment'
import './style.scss'
import store from "@/store/store"

const { RangePicker } = DatePicker
const { Option } = Select
const { TextArea } = Input
const { Search } = Input
export default class TakeStock extends Component {
    constructor() {
        super()
        this.addFormRef = React.createRef()
        this.addBeforeFormRef = React.createRef()
        this.state = {
            goodsList: [],
            userName: '',
            librarys: [],
            columns: [
                {
                    title: "序号",
                    dataIndex: "index",
                    key: "index",
                    render:(text,record,index) =>{
                        return((this.state.pageData.pageNo - 1)*(this.state.pageData.pageSize) + (index + 1));
                    }
                },
                {
                    title: "物品名称",
                    dataIndex: "goodsName",
                    key: "goodsName",

                },
                {
                    title:'物料名称',
                    dataIndex:'materialName',
                    key:'materialName'
                },
                {
                    title: "规格",
                    dataIndex: "sku",
                    key: "sku",

                },

                {
                    title: "库存量",
                    dataIndex: "oldCount",
                    key: "oldCount",

                },
                {
                    title: "实盘数",
                    dataIndex: "nowCount",
                    key: "nowCount",

                },
                {
                    title: "盈亏量",
                    dataIndex: "count",
                    key: "count",

                }, {
                    title: "操作",
                    dataIndex: "serviceShowFile",
                    key: "serviceShowFile",
                    render: (text, render, index) => {
                        return <div>
                            <TheButton haspermi={['storage:putIn:view']} onClick={() => this.del(render.id, index)}>删除</TheButton>
                        </div>
                    }
                },

            ],
            dataSource: [],
            searchDataSource:[],
            pageData: {
                pageNo: 1,
                pageSize: 10

            },
            total: 0,
            isModalVisible: false,
            loading: false,
            isSave: false,
            id: null,
            libraryId: '',
            libraryName: '',
            modalTitle: "",
            productSku: {},
            currentSku: {},
            materialId:'',
            skuId: '',
            details: {},
            mode: 'normal'
        }
    }
    componentDidMount() {
        let id = this.props.match.params.id
        let mode = this.props.match.params.mode
        if (mode === 'normal') this.state.columns.pop()


        this.setState({
            id: id === 'null' ? '' : id,
            mode: mode,
        }, async () => {
            await this.getAddBefore()
            if (this.state.id) {
                await this.getView(this.state.id)
            }


        })
    }
    async getView(id) {
        let res = await apiStockTakeListView({ id })
        if (res.code === 0) {
            this.setState({
                details: res.data,
                isSave: true,
                code: res.data.stockTake.code,
                dataSource: res.data.list,
                searchDataSource:res.data.list,
                libraryId:res.data.stockTake.libraryId,
            }, () => {
                this.addBeforeFormRef.current.setFieldsValue({
                    date: moment(res.data.stockTake.createTime),
                    userName: res.data.stockTake.userName,
                    libraryId: res.data.stockTake.libraryId,
                    remark: res.data.stockTake.remark,
                })
                let values = this.addBeforeFormRef.current.getFieldsValue()
                this.getGoodsList(values.libraryId)
            })
        }
    }
    async getGoodsList(libraryId) {
        let res = await apiGetGoodsList({ libraryId, type: 1 })
        if (res.code === 0) {
            this.setState({
                goodsList: res.data
            })
        }
    }
    async del(id, index) {
        console.log(id, index);
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "确定是否删除？",
            onOk: async () => {
                let res = await apiStockTakeInfoDel({ id })
                if (res.code === 0) {
                    let dataSource = this.state.dataSource
                    dataSource.splice(index, 1)
                    this.setState({
                        searchDataSource: []
                    }, () => {
                        this.setState({
                            searchDataSource:dataSource
                        })
                    })

                    React.$message({
                        type: 'success',
                        content: res.codeMessage
                    })
                } else {
                    React.$message({
                        type: 'warning',
                        content: res.codeMessage
                    })
                }
            }
        });

    }
    async getAddBefore() {
        let res = await apiStockTakeListAddBefore()
        if (res.code === 0) {
            if (!res.data.librarys || res.data.librarys === 0) {
                store.dispatch({
                    type: 'SavePageTabValue',
                    data: {
                        tab: 'store'
                    }
                })
                Modal.warning({
                    title: '提示',
                    content: '尚未创建仓库，是否立即添加仓库？',
                    okText: '去添加',
                    onOk:()=>{
                        this.props.history.push('/storageManager/store')
                    }
                });
                return
            }
            this.setState({
                librarys: res.data.librarys,
                userName: res.data.userName
            }, () => {
                if (!this.state.id) {
                    this.addBeforeFormRef.current.setFieldsValue({
                        date: moment(),
                        userName: res.data.userName,
                        libraryId: res.data.librarys.length > 0 && res.data.librarys[0].id
                    })
                    let values = this.addBeforeFormRef.current.getFieldsValue()
                    this.getGoodsList(values.libraryId)
                }

            })

        }
    }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getData()
        })
    };
    onCancel() {
        this.resetAddForm()
        this.setState({
            isModalVisible: false
        })
    }
    async onFinishAdd(values) {
        let res = await apiStockTakeInfoAdd({
            stockTakeId: this.state.id,//盘点单id
            code: this.state.code,//盘点单号
            goodId: this.state.productSku.goodsInfo.goodsId,//商品id
            goodsSkuId: this.state.currentSku.SKUId,//skuId
            oldCount: this.state.currentSku.stock,//当前库存
            nowCount: values.nowCount,//盘点库存
        })
        if (res.code === 0) {
            message.success(res.codeMessage);
            this.resetAddForm()
            this.setState({
                searchDataSource:this.state.dataSource.concat(res.data),
                dataSource: this.state.dataSource.concat(res.data),
                isModalVisible: false
            })

        }

    }
    resetAddForm() {
        this.addFormRef.current.setFieldsValue({
            nowCount: null,
            goodsId: ''
        })
        this.setState({
            productSku: {},
            currentSku: {}
        })
    }
    async saveAddBefore(values) {

        let library = this.state.librarys.filter(item => item.id === values.libraryId)[0]
        let res = await apiStockTakeListAdd({
            libraryId: library.id,
            libraryName: library.name,
            remark: values.remark ? values.remark : '',
        })
        if (res.code === 0) {
            message.success(res.codeMessage);

            this.setState({
                isSave: true,
                libraryName: library.name,
                id: res.data.id,
                libraryId:library.id,
                modalTitle: `在【${library.name}】出库`
            })
        }
    }
    async execute(executeType) {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "是否确定操作？",
            onOk: async () => {
                let res = await apiStockTakeListExecute({
                    type: executeType,
                    id: this.state.id
                })
                if (res.code === 0 && res.data.code == 0) {

                    React.$message({
                        type: 'success',
                        content: res.codeMessage
                    })
                    setTimeout(() => {
                        this.props.history.go(-1)
                    }, 2000);

                } else if (res.code === 0 && res.data.code == 1) {
                    let columns = [
                        {
                            title: '商品名称',
                            dataIndex: 'goodsName',
                            key: 'goodsName',
                        },
                        {
                            title: '规格',
                            dataIndex: 'sku',
                            key: 'sku',
                        },
                        {
                            title: '盘点后库存',
                            dataIndex: 'nowCount',
                            key: 'nowCount',
                        },
                        {
                            title: '待出库存',
                            dataIndex: 'waiteOutCount',
                            key: 'waiteOutCount',
                        }]
                    let data = res.data.list
                    Modal.warning({
                        width: '50%',
                        title: '以下商品无法盘点，待出库数量大于盘点数量！',
                        content: (<Table bordered pagination={false} columns={columns} dataSource={data} style={{maxHeight:'60vh',overflowY:'auto'}} />),
                    });

                }
            }
        });




    }
    addGoods() {
        this.setState({
            isModalVisible: true
        })
    }
    handleCancel() { }
    savePutInOrder = () => {
        Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: '保存盘点单后将不可更改，确定保存盘点单吗?',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                this.setState({
                    isSave: true
                })
            }
        });
    }
    selectFilter(input, option) {
        const materialIds = option.option.materialIds.toLowerCase().split(',')
        const result = option.children.toLowerCase().includes(input.toLowerCase()) || materialIds.includes(input.toLowerCase())
        return result
    }
    goodsChange(e, row) {
        this.apiGetGoodsDetail(e)
    }
    async apiGetGoodsDetail(goodsId, skuId) {
        let res = await apiGetGoodsDetail({ goodsId,libraryId:this.state.libraryId})
        if (res.code === 0) {
            if (this.state.materialId) {
                let result = res.data.skuInfo.filter(item => item.materialId === this.state.materialId)
                this.setState({
                    productSku: res.data,
                    currentSku: result.length > 0 ? result[0] : res.data.skuInfo[0]
                })
            } else {
                this.setState({
                    productSku: res.data,
                    currentSku: res.data.skuInfo[0]
                })
            }

        }
    }
    triggerSkuTag(row) {
        // if (this.state.skuId !== 'null') {
        //     return
        // }
        this.setState({
            currentSku: row
        })
    }
    resolve() {
        this.execute(2)
    }
    reject() {
        this.execute(3)
    }
    change(e){
        this.getGoodsList(e)
    }
    onBlur = (materialId) => {
        this.setState({
            materialId
        })
    }
    getSearchData(aim,searchVal){
        let newArr =[]
        for (var i = 0; i < aim.length; i++) {
            let value = aim[i].goodsName, value2 = aim[i].materialName
            if (value.includes(searchVal) || value2.includes(searchVal)) {
                newArr.push(aim[i]);//将值放入第二个数组
            }
        }
        return newArr
        // return aim.filter(item => item.goodsName == goodsName)
    }
    setSearchValue = (value) =>{
        const {dataSource} = this.state
        let search =  value.target.value.trim()
        if(search){
            this.setState({
                searchDataSource:this.getSearchData(dataSource,search)
            })
        }else{
            this.setState({
                searchDataSource:this.state.dataSource
            })
        }
    }
    render() {
        let { currentSku, skuId, productSku, details, mode, goodsList, columns, dataSource, pageData, total, isModalVisible, loading, isSave, modalTitle, userName, librarys,searchDataSource } = this.state
        return (
            <div className="p-layout-box">
                <GoBack history={this.props.history} title="盘点" />
                <Form layout={'inline'} ref={this.addBeforeFormRef} onFinish={(values) => this.saveAddBefore(values)} style={{ marginBottom: 12, marginTop: 12 }}>
                    <Form.Item name={"date"}>
                        <DatePicker disabled={this.state.id} format="YYYY-MM-DD HH:mm:ss" style={{
                            width: 200,
                        }} showTime />
                    </Form.Item>
                    <Form.Item name={"libraryId"}>
                        <Select onChange={(e)=>this.change(e)} disabled={this.state.id} placeholder={"盘点仓库"} style={{ width: 140 }}>
                            {librarys.length > 0 && librarys.map(item => {
                                return <Option value={item.id}>{item.name}</Option>
                            })}
                        </Select>
                    </Form.Item>
                    {/* <Form.Item name={"userName"}>
                        <Input style={{ width: 140 }} placeholder={"登记人"} />
                    </Form.Item>
                    <Form.Item name={"remark"}>
                        <TextArea autoSize={false} rows={1} style={{ width: 340 }} maxLength={1} placeholder={"备注"} />
                    </Form.Item> */}
                    <Form.Item>
                        {
                            ['add', 'edit'].includes(mode) &&

                            <Space size="small" style={{ marginLeft: 10 }}>

                                {
                                    isSave ?
                                        <Button type="primary" onClick={() => this.addGoods()}>
                                            添加物品
                                        </Button> : <Button type="primary" htmlType="submit">
                                            保存盘点单
                                        </Button>
                                }
                            </Space>

                        }
                    </Form.Item>
                    <Space direction="vertical">
                    <Search
                        placeholder="请输入物品名称"
                        onChange={(e)=>this.setSearchValue(e)}
                        style={{
                            width: 200,
                        }}
                        allowClear
                        />
                    </Space>
                </Form>
                <TheTable
                    scroll={{ x: "max-content", y: '63vh' }}
                    columns={columns}
                    dataSource={searchDataSource}
                />

                <div style={{ textAlign: 'center', marginTop: 12 }}>
                    {
                        ['add', 'edit'].includes(mode) &&
                        <div>
                            {/* <TheButton type="default" size='middle' onClick={() => this.execute(0)}>草稿</TheButton> */}
                            {
                                dataSource.length > 0 &&
                                <TheButton style={{ marginLeft: 12 }} type="primary" size='middle' onClick={() => this.execute(1)}>提交</TheButton>

                            }
                        </div>
                    }
                    {
                        mode === 'execute' &&
                        <div>
                            <TheButton type="primary" size='middle' onClick={() => this.resolve()}>审批通过</TheButton>
                            <TheButton style={{ marginLeft: 12 }} type="warning" size='middle' onClick={() => this.reject()}>审批驳回</TheButton>
                        </div>
                    }

                </div>
                <Modal title={modalTitle} visible={isModalVisible} width="40%"

                    onCancel={() => this.onCancel()}
                    footer={null}
                >
                    <Form
                        labelCol={{
                            span: 4,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                        ref={this.addFormRef}
                        onFinish={(values) => this.onFinishAdd(values)}
                    >
                        <Row>

                            <Col span={24}>
                                <Form.Item

                                    label="选择商品"
                                    name="goodsId"
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择商品!',
                                        },
                                    ]}
                                >
                                    <Select

                                        showSearch
                                        optionFilterProp="children"
                                        filterOption={(input, option) => this.selectFilter(input, option)}
                                        style={{
                                            width: '100%',
                                        }}
                                        onSearch={(e) => this.onBlur(e)}
                                        onSelect={(e, obj) => this.goodsChange(e, obj)}
                                        placeholder="请选择商品"
                                    >
                                        {
                                            goodsList.map(item => <Option option={item} key={item.goodsId} value={item.goodsId}>{item.goodsName}</Option>)
                                        }
                                    </Select>

                                </Form.Item >
                            </Col>

                            <Col>
                                {
                                    productSku.hasOwnProperty('goodsInfo') ?
                                        <Form.Item
                                            wrapperCol={{
                                                offset: 4,
                                                span: 16,
                                            }}
                                        >
                                            <div className='goodsDesc'>
                                                <div className='info'>
                                                    <img src={currentSku.imageFile ? currentSku.imageFile.split(',')[0] : ''} alt="商品图片" className='goodsImg' />
                                                    <div className="goodsInfo">
                                                        <div className='name'>{productSku.goodsInfo.goodsName}</div>
                                                        <div className='stock' >
                                                            物料ID：{currentSku.materialId}
                                                        </div>
                                                        <div className='stock'>
                                                            物料名称：{currentSku.materialName}
                                                        </div>
                                                        <div className='stock' >
                                                            可售库存：{currentSku.stock}
                                                        </div>
                                                        <div className='stock' >
                                                            待出库存：{currentSku.waiteOutCount}
                                                        </div>
                                                        <div className='stock' >
                                                            实际库存：{currentSku.realStock}
                                                        </div>
                                                    </div>
                                                </div>
                                                <div className='goodsSku'>
                                                    {
                                                        productSku.skuInfo.map(item =>
                                                            <Tag className='tag' key={item.SKUId} color={item.SKUId === currentSku.SKUId ? "cyan" : ''} onClick={() => this.triggerSkuTag(item)}>
                                                                {item.skuAttribute.map(item2 => item2.value).join(',')}
                                                            </Tag>
                                                        )
                                                    }

                                                </div>
                                            </div>
                                        </Form.Item> : null
                                }
                            </Col>

                            <Col span={24}>
                                <Form.Item
                                    label="实盘数"
                                    name="nowCount"
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入!',
                                        },
                                    ]}
                                >
                                    <InputNumber style={{
                                    }} precision={0} min={0} />
                                </Form.Item>
                            </Col>
                            <Col>
                                <Form.Item wrapperCol={{
                                    offset: 8,
                                    span: 16,
                                }}>
                                    <Space size="small" style={{ marginLeft: 10 }}>

                                        <Button type="default" onClick={() => this.resetAddForm()}>
                                            重置
                                        </Button>
                                        <Button type="primary" htmlType="submit">
                                            确定
                                        </Button>
                                    </Space>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Modal>
            </div >
        );
    }
}
